package com.springcloud.hystrixdemo.config

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.lang.Nullable
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Configuration
class WebConfig implements WebMvcConfigurer{

    /*
     为了支持Hystrix的缓存以及请求聚合功能,需要在请求时初始化Hystrix的上下文
    */

    @Override
    void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(
                new HandlerInterceptor(){
                    @Override
                    boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

                        //初始化Hystrix上下文
                        def context=HystrixRequestContext.initializeContext()
                        request.setAttribute('HystrixRequestContext',context)
                        true
                    }

                    @Override
                    void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

                        //请求结束时关闭上下文
                        ((HystrixRequestContext)request.getAttribute('HystrixRequestContext')).close()
                    }
                }
        )
    }
}
